package com.lagou.config;

import com.lagou.code.RpcDecoder;
import com.lagou.entity.RpcRequest;
import com.lagou.handler.UserServiceHandler;
import com.lagou.serializer.impl.JSONSerializer;
import com.lagou.service.UserServiceImpl;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class ServerBootConfig {

//    public static void main(String[] args) throws InterruptedException {
//        //启动服务器
//        UserServiceImpl.startServer("127.0.0.1",8999);
//    }

    @Bean
    public void init()  {
        System.out.println("开始初始化服务端，监听端口8999");
        //启动服务器
        try {
            startServer("127.0.0.1",8999);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    //创建一个方法启动服务器
    public void startServer(String ip , int port) throws InterruptedException {
        //1.创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup  workGroup = new NioEventLoopGroup();

        //2.创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //3.配置启动引导对象
        serverBootstrap.group(bossGroup,workGroup)
                //设置通道为NIO
                .channel(NioServerSocketChannel.class)
                //创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        //给管道对象pipeLine 设置编码
                        pipeline.addLast(new StringEncoder());
//                        pipeline.addLast(new StringDecoder());
                        // 把接收的参数按RpcDecoder规则解码
                        pipeline.addLast(new RpcDecoder(RpcRequest.class,
                                new JSONSerializer()));
                        //把我们自顶一个ChannelHander添加到通道中
                        pipeline.addLast(new UserServiceHandler());
                    }
                });

        //4.绑定端口
        serverBootstrap.bind(port).sync();
    }
}
